<template>
  <div class="step-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>步骤列表</span>
          <el-button type="primary" @click="openCreateStepModal" style="float: right;">添加步骤</el-button>
        </div>
      </template>
      <el-table :data="steps" style="width: 100%">
        <el-table-column prop="stepOrder" label="顺序" width="80"></el-table-column>
        <el-table-column prop="type" label="类型" :formatter="typeFormatter" width="100"></el-table-column>
        <el-table-column prop="target" label="目标元素"></el-table-column>
        <el-table-column prop="inputContent" label="输入内容"></el-table-column>
        <el-table-column prop="waitTime" label="等待时间（秒）"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog title="添加步骤" v-model="createStepModalVisible">
      <el-form :model="newStep" label-width="120px">
        <el-form-item label="顺序">
          <el-input-number v-model="newStep.stepOrder" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="newStep.type" placeholder="请选择类型">
            <el-option label="点击" :value="0"></el-option>
            <el-option label="输入" :value="1"></el-option>
            <el-option label="执行代码" :value="2"></el-option>
            <el-option label="打开网址" :value="3"></el-option>
            <el-option label="输入文本" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目标元素" v-if="newStep.type === 0 || newStep.type === 1 || newStep.type === 4">
          <el-input v-model="newStep.target" placeholder="CSS Selector, XPath, or Regex"></el-input>
        </el-form-item>
        <el-form-item label="网址" v-if="newStep.type === 3">
          <el-input v-model="newStep.target" placeholder="请输入网址"></el-input>
        </el-form-item>
        <el-form-item label="输入内容" v-if="newStep.type === 1 || newStep.type === 4">
          <el-input type="textarea" v-model="newStep.inputContent"></el-input>
        </el-form-item>
        <el-form-item label="执行代码" v-if="newStep.type === 2">
          <el-input type="textarea" v-model="newStep.code"></el-input>
        </el-form-item>
        <el-form-item label="等待时间（秒）">
          <el-input-number v-model="newStep.waitTime" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createStepModalVisible = false">取 消</el-button>
          <el-button type="primary" @click="createStep">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="编辑步骤" v-model="editStepModalVisible">
      <el-form :model="currentStep" label-width="120px">
        <el-form-item label="顺序">
          <el-input-number v-model="currentStep.stepOrder" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="currentStep.type" placeholder="请选择类型">
            <el-option label="点击" :value="0"></el-option>
            <el-option label="输入" :value="1"></el-option>
            <el-option label="执行代码" :value="2"></el-option>
            <el-option label="打开网址" :value="3"></el-option>
            <el-option label="输入文本" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目标元素" v-if="currentStep.type === 0 || currentStep.type === 1 || currentStep.type === 4">
          <el-input v-model="currentStep.target" placeholder="CSS Selector, XPath, or Regex"></el-input>
        </el-form-item>
        <el-form-item label="网址" v-if="currentStep.type === 3">
          <el-input v-model="currentStep.target" placeholder="请输入网址"></el-input>
        </el-form-item>
        <el-form-item label="输入内容" v-if="currentStep.type === 1 || currentStep.type === 4">
          <el-input type="textarea" v-model="currentStep.inputContent"></el-input>
        </el-form-item>
        <el-form-item label="执行代码" v-if="currentStep.type === 2">
          <el-input type="textarea" v-model="currentStep.code"></el-input>
        </el-form-item>
        <el-form-item label="等待时间（秒）">
          <el-input-number v-model="currentStep.waitTime" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editStepModalVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateStep">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'StepList',
  data() {
    return {
      taskId: this.$route.params.id,
      steps: [],
      createStepModalVisible: false,
      editStepModalVisible: false,
      newStep: {
        taskId: this.$route.params.id,
        stepOrder: 1,
        type: null,
        target: '',
        inputContent: '',
        code: '',
        waitTime: 0
      },
      currentStep: {
        id: null,
        taskId: this.$route.params.id,
        stepOrder: 1,
        type: null,
        target: '',
        inputContent: '',
        code: '',
        waitTime: 0
      }
    };
  },
  mounted() {
    this.fetchSteps();
  },
  methods: {
    fetchSteps() {
      axios.get('/api/step', {
        params: {
          taskId: this.taskId
        },
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
      .then(response => {
        this.steps = response.data;
      })
      .catch(error => {
        console.error('Error fetching steps:', error);
      });
    },
    openCreateStepModal() {
      this.newStep = {
        taskId: this.taskId,
        stepOrder: 1,
        type: null,
        target: '',
        inputContent: '',
        code: '',
        waitTime: 0
      };
      this.createStepModalVisible = true;
    },
    createStep() {
      axios.post('/api/step', this.newStep, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
      .then(response => {
        this.createStepModalVisible = false;
        this.fetchSteps();
      })
      .catch(error => {
        console.error('Error creating step:', error);
      });
    },
    handleEdit(step) {
      this.currentStep = { ...step };
      this.editStepModalVisible = true;
    },
    updateStep() {
      axios.put(`/api/step/${this.currentStep.id}`, this.currentStep, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      })
      .then(response => {
        this.editStepModalVisible = false;
        this.fetchSteps();
      })
      .catch(error => {
        console.error('Error updating step:', error);
      });
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该步骤, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`/api/step/${id}`, {
          headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
          }
        })
        .then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.fetchSteps();
        })
        .catch(error => {
          console.error('Error deleting step:', error);
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    typeFormatter(row) {
      switch (row.type) {
        case 0:
          return '点击';
        case 1:
          return '输入';
        case 2:
          return '执行代码';
        case 3:
          return '打开网址';
        case 4:
          return '输入文本';
        default:
          return '未知类型';
      }
    }
  }
};
</script>

<style scoped>
.step-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 